package com.hundsun.s3.mrs.core.endpoint.listener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hundsun.s3.mrs.core.CoreManager;
import com.hundsun.s3.mrs.core.endpoint.CoreEndPoint;
import com.hundsun.s3.mrs.core.endpoint.EndPointStarter;
import com.hundsun.s3.mrs.core.repeater.CoreRepeater;
import com.hundsun.s3.mrs.pub.utils.FileUtils;

public class EndPointListener implements ServletContextListener {
	private static final Logger LOG = LoggerFactory.getLogger(EndPointListener.class);
	
	private static final String ALL_THREADS = "all threads";
	
	public void contextDestroyed(ServletContextEvent sce) {
		ServletContext servletContext = sce.getServletContext();
		// 销毁各个线程
		@SuppressWarnings("unchecked")
		List<Thread> allThreads = (List<Thread>) servletContext.getAttribute(ALL_THREADS);
		Iterator<Thread> iterator = allThreads.iterator();
		Thread t;
		while(iterator.hasNext()) {
			t = iterator.next();
			if(t.isAlive()) {
				t.interrupt();
			}
		}
	}

	public void contextInitialized(ServletContextEvent sce) {
		ServletContext servletContext = sce.getServletContext();
		String tryCountStr = servletContext.getInitParameter("tryCount");
		String coreRepeaterCountStr = servletContext.getInitParameter("coreRepeaterCount");
		int tryCount;
		int coreRepeaterCount;
		try {
			if(StringUtils.isBlank(tryCountStr)) {
				tryCount = 30;
			} else {
				tryCount = Integer.valueOf(tryCountStr);
			}
		} catch(Exception e) {
			LOG.warn("tryCount参数错误，tryCount被设置为默认值30");
			tryCount = 30;
		}
		try {
			if(StringUtils.isBlank(coreRepeaterCountStr)) {
				coreRepeaterCount = 1;
			} else {
				coreRepeaterCount = Integer.valueOf(coreRepeaterCountStr);
			}
		} catch(Exception e) {
			LOG.warn("coreRepeaterCount参数错误，coreRepeaterCount被设置为默认值5");
			coreRepeaterCount = 5;
		}
		
		List<Thread> allThreads = new ArrayList<>();
		
		// 开启websocket终端
		Thread endPointThread = new Thread(new EndPointStarter(tryCount));
		endPointThread.setName(CoreEndPoint.ENDPOINT_NAME);
		endPointThread.start();
		allThreads.add(endPointThread);
		
		Thread coreRepeaterThread;
		// 开启核心转发器线程
		for(int i=1; i<=coreRepeaterCount; i++) {
			coreRepeaterThread = new Thread(new CoreRepeater());
			coreRepeaterThread.setName(CoreRepeater.CORE_REP_NAME);
			coreRepeaterThread.start();
			allThreads.add(coreRepeaterThread);
			LOG.info("成功开启Core转发器线程，当前Core转发器线程数为：" + i);
		}
		servletContext.setAttribute(ALL_THREADS, allThreads);
		
		//加载各种处理器
		try {
			CoreManager.initMappers(FileUtils.files("*type2handler.xml"));
			CoreManager.initChains(FileUtils.files("*chain.xml"));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
